/**
 * WebSocket管理工具类
 * 用于管理客服聊天连接
 */
import env from '@/config/env.js'
class WebSocketManager {
	constructor() {
		this.websocket = null
		this.isConnected = false
		this.username = ''
		this.reconnectTimer = null
		this.reconnectCount = 0
		this.maxReconnectCount = 3
		this.reconnectInterval = 3000 // 3秒重连间隔
		this.messageCallbacks = []
	}

	/**
	 * 建立WebSocket连接
	 * @param {string} username 用户名
	 * @param {function} onMessage 消息回调函数
	 */
	connect(username, onMessage) {
		if (this.isConnected) {
			console.log('WebSocket已连接')
			return
		}

		this.username = username
		if (onMessage) {
			this.messageCallbacks.push(onMessage)
		}

		try {
			// WebSocket连接地址
			const wsUrl = `ws://localhost:8080/Chat/chat/${this.username}`
			console.log('正在连接WebSocket:', wsUrl)

			this.websocket = uni.connectSocket({
				url: wsUrl,
				success: () => {
					console.log('WebSocket连接成功')
					this.isConnected = true
					this.reconnectCount = 0
					// 调用onopen接口
					this.callOnOpen()
				},
				fail: (error) => {
					console.error('WebSocket连接失败:', error)
					this.handleReconnect()
				}
			})

			// 监听WebSocket连接打开
			uni.onSocketOpen(() => {
				console.log('WebSocket连接已打开')
				this.isConnected = true
				this.reconnectCount = 0
			})

			// 监听WebSocket接收到服务器的消息
			uni.onSocketMessage((res) => {
				console.log('收到WebSocket消息:', res.data)
				this.handleMessage(res.data)
			})

			// 监听WebSocket错误
			uni.onSocketError((error) => {
				console.error('WebSocket错误:', error)
				this.isConnected = false
				this.handleReconnect()
			})

			// 监听WebSocket关闭
			uni.onSocketClose(() => {
				console.log('WebSocket连接已关闭')
				this.isConnected = false
				this.handleReconnect()
			})

		} catch (error) {
			console.error('建立WebSocket连接异常:', error)
			this.handleReconnect()
		}
	}

	/**
	 * 处理重连
	 */
	handleReconnect() {
		if (this.reconnectCount >= this.maxReconnectCount) {
			console.log('重连次数已达上限，停止重连')
			return
		}

		if (this.reconnectTimer) {
			clearTimeout(this.reconnectTimer)
		}

		this.reconnectTimer = setTimeout(() => {
			console.log(`第${this.reconnectCount + 1}次重连`)
			this.reconnectCount++
			this.connect(this.username)
		}, this.reconnectInterval)
	}

	/**
	 * 处理接收到的消息
	 * @param {string} data 消息数据
	 */
	handleMessage(data) {
		try {
			const messageData = JSON.parse(data)
			// 通知所有回调函数
			this.messageCallbacks.forEach(callback => {
				callback(messageData)
			})
		} catch (e) {
			// 如果不是JSON格式，直接传递原始数据
			this.messageCallbacks.forEach(callback => {
				callback({ msg: data })
			})
		}
	}

	/**
	 * 发送消息
	 * @param {string} message 消息内容
	 * @returns {Promise} 发送结果
	 */
	sendMessage(message) {
		return new Promise((resolve, reject) => {
			if (!this.isConnected) {
				reject(new Error('WebSocket未连接'))
				return
			}

			try {
				uni.sendSocketMessage({
					data: message,
					success: () => {
						console.log('消息发送成功:', message)
						// 调用onmessage接口
						this.callOnMessage(message)
						resolve()
					},
					fail: (error) => {
						console.error('消息发送失败:', error)
						reject(error)
					}
				})
			} catch (error) {
				console.error('发送消息异常:', error)
				reject(error)
			}
		})
	}

	/**
	 * 调用onopen接口
	 */
	callOnOpen() {
		console.log('调用onopen接口，用户名:', this.username)
		// 这里可以发送一个初始化消息给服务器
	}

	/**
	 * 调用onmessage接口
	 * @param {string} message 消息内容
	 */
	callOnMessage(message) {
		console.log('调用onmessage接口，消息:', message, '用户名:', this.username)
		// 这里可以发送消息到后端ChatService的onMessage方法
		// 后端会处理消息并返回响应
	}

	/**
	 * 调用onclose接口
	 */
	callOnClose() {
		console.log('调用onclose接口，用户名:', this.username)
	}

	/**
	 * 关闭WebSocket连接
	 */
	disconnect() {
		if (this.reconnectTimer) {
			clearTimeout(this.reconnectTimer)
			this.reconnectTimer = null
		}

		if (this.websocket && this.isConnected) {
			console.log('关闭WebSocket连接')
			uni.closeSocket({
				success: () => {
					console.log('WebSocket连接已关闭')
					this.isConnected = false
					// 调用onclose接口
					this.callOnClose()
				},
				fail: (error) => {
					console.error('关闭WebSocket失败:', error)
				}
			})
		}

		// 清空回调函数
		this.messageCallbacks = []
	}

	/**
	 * 添加消息回调函数
	 * @param {function} callback 回调函数
	 */
	addMessageCallback(callback) {
		this.messageCallbacks.push(callback)
	}

	/**
	 * 移除消息回调函数
	 * @param {function} callback 回调函数
	 */
	removeMessageCallback(callback) {
		const index = this.messageCallbacks.indexOf(callback)
		if (index > -1) {
			this.messageCallbacks.splice(index, 1)
		}
	}

	/**
	 * 获取连接状态
	 * @returns {boolean} 是否已连接
	 */
	getConnectionStatus() {
		return this.isConnected
	}

	/**
	 * 获取用户名
	 * @returns {string} 用户名
	 */
	getUsername() {
		return this.username
	}
}

// 创建单例实例
const webSocketManager = new WebSocketManager()

export default webSocketManager 